<?php
namespace app\mogosdk\model;
use think\Model;
use \Firebase\JWT\JWT;
use think\Config;
// 加载配置
Config::load(APP_PATH.'mogosdk/config.php');

class Mogo extends Model{
    // 继承后可以直接通过类变量得到用户id
    protected $USER_ID;
    /**
     * 通过token获取当前用户的token
     * @return object
     */
    protected function currentUser(){
        $jwt = request()->header('Authorization');
        $key = config('mogosdk_key')||'MogoSDK';
        if(!$jwt) $this->forceReturn("miss token");

        try{
            $user = JWT::decode($jwt, $key, array('HS256'));
            return $user;
        }catch (\Exception $exception){
            $this->forceReturn("token invalid");
        }
    }

    /**
     * 用户登录
     * @param $user array 需要保存的用户信息
     * @return array 返回整个用户信息包括token
     */
    protected function userLogin($user){
        $key = config('mogosdk_key')||'MogoSDK';
        $user['token'] = JWT::encode($user, $key);;
        return $user;
    }
    /**
     * 强制返回错误json
     * @param string $error
     */
    public function forceReturn($error="未登录"){
        echo json_encode(['error'=>$error]);
        header("HTTP/1.1 404 Not Found");
        header("Status: 404 Not Found");
        header('Content-type: application/json; charset=utf-8');
        exit;
    }
    
}
